package com.moli.iov.down.command.disruptor;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.dsl.ProducerType;
import com.moli.iov.disruptor.DataEventHandler;
import com.moli.iov.disruptor.DataPipeline;
import com.moli.iov.down.model.dto.remoting.CommandDto;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 *  异步 无锁 并发框架
 *
 *  单生产者、多消费者 模式
 *
 *  发送命令
 * </p>
 *
 * @author: zql
 * @Date: 2019/1/3 9:33
 */
@Slf4j
@Component
public class DisruptorProducer extends DataPipeline<List<CommandDto>> {

    /**
     * RingBuffer 大小
     */
    //@Value("${bufferSize}")
    private int bufferSize = 10;

    @PostConstruct
    public void initDisruptor(){

        setDEFAULT_BUFFER_SIZE(bufferSize > 0 ? bufferSize : 512000);

        try {

            super.init(ProducerType.MULTI, new BlockingWaitStrategy());
        } catch (Exception e) {
            log.error("initDisruptor 异常", e);
        }
    }

    @Override
    protected DataEventHandler<List<CommandDto>>[] getHandlers() {
        int handlerSize = Runtime.getRuntime().availableProcessors();
        DisruptorConsumer[] handlers = new DisruptorConsumer[handlerSize];

        for(int i = 0; i < handlerSize; i++){
            handlers[i] = new DisruptorConsumer();
        }

        return handlers;
    }

    @Override
    protected void onClose() throws Exception {
        log.info("DisruptorProducer is closing");
    }
}
